#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 作者：LastPage（一叶知秋）
# 代码开始时间：2025/10/10
import time
from appium import webdriver
from appium.options.android import UiAutomator2Options
from appium.webdriver.common.appiumby import AppiumBy
from appium.webdriver.extensions.android.nativekey import AndroidKey
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from appium.webdriver.common.touch_action import TouchAction
from SparkLite_ask import check_job_match


# ---------------- 启动 ----------------
desired_caps = {
    "platformName": "Android",
    "appium:automationName": "UiAutomator2",
    "appium:platformVersion": "12",
    "appium:deviceName": "d54cac6",
    "appium:appPackage": "com.hpbr.bosszhipin",
    "appium:appActivity": ".module.main.activity.ZpReceiveActivity",
    "appium:noReset": True,
    "appium:newCommandTimeout": 3600,
    "appium:ignoreHiddenApiPolicyError": True,
    "appium:allowTestPackages": True,
}

driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", options=UiAutomator2Options().load_capabilities(desired_caps))
time.sleep(5)


# ---------------- 登录等待 ----------------
def wait_for_login():
    print("正在检测登录状态...")
    while True:
        try:
            driver.find_element(
                AppiumBy.XPATH,
                '//android.widget.TextView[@resource-id="com.hpbr.bosszhipin:id/tv_action_name" and @text="一键登录"]'
            )
            print("👉 请先手动完成登录，完成后将自动继续...")
            time.sleep(5)
        except:
            print("✅ 登录页已关闭，视为登录成功")
            break

# ---------------- 下滑一页 ----------------
def swipe_up():
    w, h = driver.get_window_size().values()
    driver.swipe(w // 2, int(h * 0.8), w // 2, int(h * 0.2), 800)


# ---------------- 读取特定卡片的标题 ----------------
def read_phone_card(num):
    try:
        # 定位卡片容器
        read_card = f'(//android.view.ViewGroup[' \
                    f'@resource-id="com.hpbr.bosszhipin:id/cl_position"])[{num}]'
        card = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((AppiumBy.XPATH, read_card))
        )

        # 提取卡片内所有文本元素（假设第一个元素是标题，可根据实际调整）
        text_elements = card.find_elements(AppiumBy.CLASS_NAME, "android.widget.TextView")
        if not text_elements:
            return "未知岗位"

        # 岗位标题通常是卡片中最显眼的文本（这里取第一个非空文本，可根据实际UI调整）
        job_title = text_elements[0].text.strip()
        print(f"第{num}个卡片标题：{job_title}")
        return job_title  # 返回标题供后续使用

    except Exception as e:
        print(f"读取第{num}个卡片标题失败：{e}")
        return "获取失败"


# ---------------- 自动投递主流程 ----------------
# 在auto_deliver_flow中调用时，获取标题并暂存（后续可传递给代码2）
def auto_deliver_flow():
    # 让用户输入目标岗位（多个用空格/逗号分隔）
    user_input = input("请输入想投递的目标岗位（多个用空格或逗号分隔）：").strip()
    target_jobs = [j.strip() for j in user_input.replace(",", " ").split() if j.strip()]
    if not target_jobs:
        print("未输入有效岗位，退出投递")
        return

    wanted = int(input("请输入滑屏次数(滑屏一次投递4份简历)："))
    delivered = 0
    pull_down_refresh()

    for i in range(wanted):
        if i != 0:
            swipe_up()
            time.sleep(1.5)

        cards = driver.find_elements(
            AppiumBy.XPATH,
            '//android.view.ViewGroup[@resource-id="com.hpbr.bosszhipin:id/view_job_card"]'
        )

        for idx in range(1, min(5, len(cards) + 1)):
            try:
                # 1. 读取卡片标题
                job_title = read_phone_card(idx)
                if job_title in ["未知岗位", "获取失败"]:
                    print(f"第{idx}个卡片标题无效，跳过")
                    continue

                # 2. 调用AI判断是否匹配目标岗位（核心逻辑）
                is_match = check_job_match(job_title, target_jobs)
                if not is_match:
                    print(f"第{idx}个卡片岗位不匹配目标，跳过")
                    continue  # 不匹配则跳过投递

                # 3. 匹配成功，执行原有投递逻辑
                skip_xpath = f'(//android.view.ViewGroup[' \
                             f'@resource-id="com.hpbr.bosszhipin:id/view_job_card"])[{idx}]' \
                             '//android.widget.TextView[' \
                             '@resource-id="com.hpbr.bosszhipin:id/tv_employer" and @text="网申 · ' \
                             '直投"]' \
                             '//android.widget.TextView[' \
                             '@resource-id="com.hpbr.bosszhipin:id/tv_salary_statue" and ' \
                             '@text="面议"]' \
                             '//android.widget.Button[' \
                             '@resource-id="com.hpbr.bosszhipin:id/look_btn"]'

                if driver.find_elements(AppiumBy.XPATH, skip_xpath):
                    print(f"第 {idx} 个卡片为“非简历投递区域”，已跳过")
                    continue

                card_xpath = f'(//android.view.ViewGroup[' \
                             f'@resource-id="com.hpbr.bosszhipin:id/view_job_card"])[{idx}]'
                card = WebDriverWait(driver, 10).until(
                    EC.element_to_be_clickable((AppiumBy.XPATH, card_xpath))
                )

                card.click()
                if communicate_and_send():
                    delivered += 1
                safe_back(2)
            except Exception as e:
                print(f"第 {idx} 张卡片处理失败：{e}")
                safe_back(2)

    print(f"===== 投递完成！本次共投递 {delivered} 份 =====")


# ---------------- 沟通 + 发消息 ----------------
def communicate_and_send() -> bool:
    try:

        # 1. 未投递过，走正常流程
        # 立即沟通
        comm = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((AppiumBy.XPATH,
                                       '//android.widget.Button[@resource-id="com.hpbr.bosszhipin:id/btn_chat"]')))
        comm.click()

        # 2. 先判断是否已经投递过（tv_content_text 存在即视为已投递）
        if driver.find_elements(AppiumBy.XPATH,
                                '//android.widget.TextView[@resource-id="com.hpbr.bosszhipin:id/tv_content_text"]'):
            print("已经投递过")
            return False

        # 发送消息
        msg = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((AppiumBy.XPATH,
                                       '//android.widget.ImageView[@resource-id="com.hpbr.bosszhipin:id/mCommonText"]')))
        msg.click()

        send_btn = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((AppiumBy.XPATH,
                                       '(//android.widget.TextView[@resource-id="com.hpbr.bosszhipin:id/btn_send"])[2]')))
        send_btn.click()

        print("投递成功")
        return True

    except Exception as e:
        print("投递失败", e)
        return False

# ---------------- 安全返回 ----------------
def safe_back(times=2):
    for _ in range(times):
        driver.press_keycode(AndroidKey.BACK)
        time.sleep(0.8)

# ---------------- 刷新页面 ----------------
def pull_down_refresh():
    """长按刷新图标触发下拉刷新"""
    el = driver.find_element(
        AppiumBy.XPATH,
        '(//android.widget.ImageView[@resource-id="com.hpbr.bosszhipin:id/lav"])[3]'
    )
    # 长按 1.2 秒
    TouchAction(driver).long_press(el=el, duration=1200).release().perform()
    time.sleep(2)          # 等网络请求 & 动画结束
# ---------------- 极简菜单 ----------------
def mini_loop():
    while True:
        print("\n操作：1 下滑一页  |  2 返回键  |  3 自动投递  |  4 刷新页面  |  -1 退出")
        op = input("请选择：").strip()
        if op == "-1":
            print("用户退出，拜拜~")
            break
        elif op == "1":
            swipe_up()
            print("已下滑一页。")
        elif op == "2":
            driver.press_keycode(AndroidKey.BACK)
            print("已返回。")
        elif op == "3":
            auto_deliver_flow()
        elif op == "4":
            pull_down_refresh()
        elif op == "5":
            read_phone_card()
        else:
            print("无效选择，重试！")

# ---------------- 主流程 ----------------
try:
    wait_for_login()
    mini_loop()
finally:
    driver.quit()


# driver.implicitly_wait(2)          # 找元素时最多等 2 s
# xpath_target = ('//android.widget.TextView[@resource-id="android:id/title" and @text="卡包"]')
#
# # 获取屏幕尺寸
# w, h = driver.get_window_size().values()
#
# def get_cur_fingerprint():
#     """返回当前屏所有可见 item 的文本拼接，作为指纹"""
#     items = driver.find_elements(
#         AppiumBy.XPATH, '//android.widget.TextView[@resource-id="android:id/title"]')
#     return '|'.join(i.text for i in items)
#
# def swipe(direction='up'):
#     """direction='up' 上滑，其他值下滑"""
#     if direction == 'up':
#         driver.swipe(w*0.5, h*0.8, w*0.5, h*0.3, 600)
#     else:
#         driver.swipe(w*0.5, h*0.3, w*0.5, h*0.8, 600)
#
# # 默认先往上滑
# direction = 'up'
# last_fingerprint = get_cur_fingerprint()
#
# while True:
#     # 先找一次，找到了就点
#     try:
#         driver.find_element(AppiumBy.XPATH, xpath_target).click()
#         print("已点击 服务与反馈")
#         break
#     except Exception:
#         pass          # 没找到就继续滑
#
#     # 执行滑动
#     swipe(direction)
#     time.sleep(0.8)   # 等动画停
#
#     # 计算新指纹
#     new_fingerprint = get_cur_fingerprint()
#
#     if new_fingerprint == last_fingerprint:
#         # 指纹没变 → 滑不动了，换方向
#         direction = 'down' if direction == 'up' else 'up'
#         print("到顶/到底，换方向 ->", direction)
#         swipe(direction)          # 立刻反向再滑一次，避免死循环
#         time.sleep(0.8)
#         new_fingerprint = get_cur_fingerprint()  # 重新取样
#
#     last_fingerprint = new_fingerprint